package engine.guide
{
	import engine.GameData;
	import engine.data.BindManage;
	import engine.data.ModelLocator;
	import engine.data.RoleVo;
	import engine.event.SceneEvent;
	import engine.net.event.CustomMsgEvent;
	import engine.net.messages.CustomToClientFlag;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	import engine.ui.lite.BaseUI;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.utils.getDefinitionByName;
	
	import newx.StageInfo;
	import newx.com.config.StaticIni;

	public class GuideManage
	{
		//新手引导的所有函数
		private var _guildFuncs 	: Array = [];
		
		//需要满足的函数
		private var _needFuncs 	: Array = [];
		
		//需要满足的参数 
		private var _needPars 		: Array = [];
		
		private var _model			: ModelLocator;
		
		//当前步骤
		private var _curStep		: String = "91001"; 
		
		//下一步骤
		private var _nextStep		: String;
		
		private var _roleObj		: RoleVo;
		
		private var _i				: int;
		
		private var _uiObject		: Object;
		
		private static var self	: GuideManage;
		
		public static function getInstance():GuideManage
		{
			if(self	==	null)
			{
				self	=	new GuideManage();
			}
			return self;
		}
		
		public function GuideManage()
		{
			_model = ModelLocator.getInstance();
			
			//和要求一一对应
			_guildFuncs = [ 
							null,
							clickNpc,
							showUI,
							clickButton,
							resultMsg,
							npcTaskResult,
							clickMouse,
							intoScene,
							acceptTask,
							completeTask,
							killMonster,
							fillLevel,
							hideUI,
							completeStory,
						];
			
			_model.addEventListener( SceneEvent.SceneLoaded, onSceneLoaded );
			
			BindManage.getInstance().BindProp(_model.scene.Role,"Level",this,"levelChenge");
		}
		
		public function set levelChenge(val:int):void
		{
			var obj:Object = StaticIni.getIniObj("guide_"+val);
			if(obj!=null)
			{
				
				StageInfo.mainSpace.tabEnabled	=	false;
				StageInfo.mainSpace.tabChildren	=	false;
				
				_roleObj = _model.scene.Role;
				
				_uiObject = StaticIni.getIniObj( "UIRegedit" );
				
				getNextGuide(obj.step);
				
				SystemSender.getInstance().CustomMsg( CustomToServerFlag.CLIENT_CUSTOMMS_SET_GUIDE_STEP, _curStep, 1 );
				_model.removeEventListener( SceneEvent.SceneLoaded, onSceneLoaded );
				
			}
		}
		
		private function onSceneLoaded( evt : Event ):void
		{
			StageInfo.mainSpace.tabEnabled	=	false;
			StageInfo.mainSpace.tabChildren	=	false;
			
			_model.removeEventListener( SceneEvent.SceneLoaded, onSceneLoaded );
			
			_roleObj = _model.scene.Role;
			
			_uiObject = StaticIni.getIniObj( "UIRegedit" );
			
			if( !_roleObj.CheckProperties( "GuideStep" ) || 0 == _roleObj.GetPropertiesEx( "GuideStep" ) )
			{
				return;
			}
			//判断是否满足了当前指引，但是由于掉线后，需要重来
			_curStep =	_roleObj.GetPropertiesEx( "GuideStep" );
			
//			if(  1 == _roleObj.GetPropertiesEx( "GuideFlg" ) )
//			{//完成
//				_model.dispatchEvent( new GuideEvent( GuideEvent.EXECUTE_GUILD, [ _curStep ] ) );
//				
//				getNextGuide( StaticIni.getIniVar( _curStep, "NextStep" ) );
//			}else
//			{
			
				getNextGuide(_curStep);
//			}
		}
		
		public function get curstep():String
		{
			return _curStep;
		}
//		要求类型
//		1：点击NPC
//		2：打开界面
//		3：点击某按钮
//		4：服务器返回某消息
//		5：NPC对话框反馈
//		6：鼠标单击
//		7：进入某场景
//		8：接取某任务
//		9：完成某任务 
//		10：击杀特定目标
//		11：到达指定等级
//		12：关闭某界面
//		13：完成某段剧情
		/**
		 *	执行新手引导 
		 */		
		public function getNextGuide( step : String ):void
		{
			_curStep =	step;
			
			if( _curStep == "0" )return;
			
			var guildObj	: Object = StaticIni.getIniObj( _curStep );
			if(guildObj == null)
			{
//				trace("没找到引导:"+_curStep);
				return;
			}
			//需求类型
			var touchTypes	: Array = guildObj.TouchType.split( "," ); 
			//需求参数			
			_needPars = guildObj.TouchPara.split( "," ); 
			
			_needFuncs = [];
			
			for each( var type : int in touchTypes )
			{
				_needFuncs.push( _guildFuncs[ type ] );
			}
			
			for( _i = 0; _i < _needFuncs.length; _i++ )
			{
				_needFuncs[ _i ]( _needPars[ _i ] );
			}
			
			
//			SystemSender.getInstance().CustomMsg( CustomToServerFlag.CLIENT_CUSTOMMS_SET_GUIDE_STEP, _curStep, -1 );
		}
		
		/**
		 *	是否满足条件 
		 * @param msgId
		 * @param pList
		 * 
		 */		
		private function fillGuide( func : Function ):void
		{
			var len : int = _needFuncs.length;
			
			for( var i : int = 0; i < len; i++ )
			{
				if( _needFuncs[ i ] == func )
				{
					_needFuncs.splice( i , 1 );
					_needPars.splice( i , 1 );
					_i --;
					break;
				}
			}
			
			if( 0 == _needFuncs.length )
			{
				//发出执行流程
				_model.dispatchEvent( new GuideEvent( GuideEvent.EXECUTE_GUILD, [ _curStep ] ) );
				
				SystemSender.getInstance().CustomMsg( CustomToServerFlag.CLIENT_CUSTOMMS_SET_GUIDE_STEP, StaticIni.getIniVar( _curStep, "NextStep" ), 1 );
				
				getNextGuide( StaticIni.getIniVar( _curStep, "NextStep" ) );
			}
		}
		
		public var clickNpcRes:Function;
		
		/**
		 * 	点击某npc
		 */		
		private function clickNpc( configId : int ):void
		{
			_model.addEventListener( String( CustomToClientFlag.SERVER_CUSTOMMSG_NPC_SELECT ),clickNpcResult );
			
			function clickNpcResult( evt : CustomMsgEvent ):void
			{
				if( evt.pList[ 0 ] == configId )
				{
					_model.removeEventListener( String( CustomToClientFlag.SERVER_CUSTOMMSG_NPC_SELECT ), clickNpcResult );
					
					fillGuide( clickNpc );
				}
			}
			clickNpcRes = clickNpcResult;
		}
		
		/**
		 *	打开某界面 
		 */		
		private function showUI( uiID : String ):void
		{
			_model.addEventListener( GuideEvent.SHOW_UI, showUIResult );
			function showUIResult( evt : GuideEvent ):void
			{
				if( _uiObject[ "UI_" + evt.data[ 0 ] ] == uiID )
				{
					_model.removeEventListener( GuideEvent.SHOW_UI, showUIResult );
					
					fillGuide( showUI );
				}
			}
		}
		
		/**
		 *	关闭界面 
		 */		
		private function hideUI( uiID : String ):void
		{
			_model.addEventListener( GuideEvent.HIDE_UI, hideUIResult );
			
			function hideUIResult( evt : GuideEvent ):void
			{
				if( _uiObject[ "UI_" + evt.data[ 0 ] ] == uiID )
				{
					_model.removeEventListener( GuideEvent.HIDE_UI, hideUIResult );
					
					fillGuide( hideUI );
				}
			}
		}
		
		/**
		 *	点击某按钮 
		 */		
		private function clickButton( uiButton : String ):void
		{
			var uiName : String = uiButton.split( ":" )[ 0 ];
			var btnName : String = uiButton.split( ":" )[ 1 ];
			
			var ui : BaseUI;
			
			if(uiName)
			{
				try
				{
					var UIClass		:Class	=getDefinitionByName("engine.newUi." + uiName) as Class;
					
					if( UIClass.hasOwnProperty( "getInstance" ) )
					{
						ui	=	UIClass.getInstance() as BaseUI;
					}else
					{
						ui	=	UIClass.getInstance()["ui"] as BaseUI;
					}
				}
				catch(e:*){}
			}
			
			( ui[ btnName ] as DisplayObject ).addEventListener( MouseEvent.CLICK, clickButtonResult );
			
			function clickButtonResult( evt : MouseEvent ):void
			{
				( ui[ btnName ] as DisplayObject ).removeEventListener( MouseEvent.CLICK, clickButtonResult );
				
				fillGuide( clickButton );
			}
		}
		
		/**
		 *	服务端返回消息 
		 */		
		private function resultMsg( msgId : String ):void
		{
			_model.addEventListener( msgId, resultMsgResult );
			
			function resultMsgResult( evt : CustomMsgEvent ):void
			{
				_model.removeEventListener( msgId, resultMsgResult );
				
				fillGuide( resultMsg );
			}
		}
		
		/**
		 *	npc对话反馈
		 */		
		private function npcTaskResult():void
		{//暂时不需要
			
		}
		
		/**
		 *	鼠标点击 
		 * 
		 */		
		private function clickMouse():void
		{
			StageInfo.stage.addEventListener( MouseEvent.CLICK, clickMouseResult );
			
			function clickMouseResult():void
			{
//				StageInfo.stage.removeEventListener( MouseEvent.CLICK, clickMouseResult );
				
				fillGuide( clickMouse );
			}
		}
		
		/**
		 *	进入某场景 
		 */		
		private function intoScene( sceneID : String ):void
		{
//			trace(GameData.SceneConfig)
			if( String(GameData.SceneConfig) == sceneID )
			{
				fillGuide( intoScene );
				return;
			}
			
			_model.addEventListener( GuideEvent.SWITCH_SCENE,intoSceneResult );
			
			function intoSceneResult( evt : GuideEvent ):void
			{
				//关闭新手引导
//				_model.dispatchEvent( new GuideEvent( GuideEvent.CLOSE_GUIDE,[] ) );
				if( evt.data[ 0 ] == sceneID )
				{
					_model.removeEventListener( GuideEvent.SWITCH_SCENE, intoSceneResult );
					
					fillGuide( intoScene );
				}
			}
		}
		
		/**
		 *	接收某任务 
		 */		
		private function acceptTask( taskId : String ):void
		{
			_model.addEventListener( String( CustomToClientFlag.SERVER_CUSTOMMSG_TASK_ACCEPT_SUCCESS ), acceptTaskResult );
		
			function acceptTaskResult( evt : CustomMsgEvent ):void
			{
				if( evt.pList[ 0 ] == taskId )
				{
					_model.removeEventListener( String( CustomToClientFlag.SERVER_CUSTOMMSG_TASK_ACCEPT_SUCCESS ), acceptTaskResult );
					
					fillGuide( acceptTask );
				}
			}
		}
		
		/**
		 *	完成某任务 
		 */		
		private function completeTask( taskId : String ):void
		{
			_model.addEventListener( String( CustomToClientFlag.SERVER_CUSTOMMSG_TASK_COMPLETE_SUCCESS ), completeTaskResult );
			
			function completeTaskResult( evt : CustomMsgEvent ):void
			{
				if( evt.pList[ 0 ] == taskId )
				{
					_model.removeEventListener( String( CustomToClientFlag.SERVER_CUSTOMMSG_TASK_COMPLETE_SUCCESS ), completeTaskResult );
					
					fillGuide( completeTask );
				}
			}
		}
		
		/**
		 *	击杀特定目标 
		 */		
		private function killMonster( configId : String ):void
		{
			_model.addEventListener( String( CustomToClientFlag.SERVER_CUSTOMMSG_FB_KILL_BOSS ), killMonsterResult );
			
			function killMonsterResult( evt : CustomMsgEvent ):void
			{
				if( evt.pList[ 0 ] == configId )
				{
					_model.removeEventListener( String( CustomToClientFlag.SERVER_CUSTOMMSG_FB_KILL_BOSS ), killMonsterResult );
					
					fillGuide( killMonster );
				}
			}
		}
		
		private var levelindex:int = -1;
		private var indexLevel:String = "";
		/**
		 *	到达指定等级 
		 */		
		private function fillLevel( level : String ):void
		{
			if( _roleObj.getPlayerLevel()+"" == level )
			{
				BindManage.getInstance().UnbindProp(_model.scene.Role,"Level",levelindex);
				fillGuide( fillLevel );
				return;
			}
			
//			_model.addEventListener( String( CustomToClientFlag.SERVER_CUSTOMMSG_PROP_CHANGE ), fillLevelResult );
			indexLevel = level;
			levelindex = BindManage.getInstance().BindProp(_model.scene.Role,"Level",this,"fillLevelResult");
			
//			function fillLevelResult( evt : CustomMsgEvent ):void
//			{
//				
//				if( evt.pList[ 0 ] == "Level" && _roleObj.getPlayerLevel()+"" == level )
//				{
//					_model.removeEventListener( String( CustomToClientFlag.SERVER_CUSTOMMSG_PROP_CHANGE ), fillLevelResult );
//					
//					fillGuide( fillLevel );
//				}
//			}
		
		}
		
		public function set fillLevelResult( val:int ):void
		{
			
//			if( evt.pList[ 0 ] == "Level" && _roleObj.getPlayerLevel()+"" == level )
			if(val.toString() == indexLevel )
			{
				BindManage.getInstance().UnbindProp(_model.scene.Role,"Level",levelindex);
//				_model.removeEventListener( String( CustomToClientFlag.SERVER_CUSTOMMSG_PROP_CHANGE ), fillLevelResult );
				
				fillGuide( fillLevel );
			}
		}
		
		/**
		 *	完成某剧情 
		 */		
		private function completeStory( storyId : String ):void
		{
			_model.addEventListener( GuideEvent.COMPLETE_STORY, completeStoryResult );
			
			function completeStoryResult( evt : GuideEvent ):void
			{
				if( evt.data[ 0 ] == "Story_"+storyId )
				{
					_model.removeEventListener( GuideEvent.COMPLETE_STORY, completeStoryResult );
					
					fillGuide( completeStory );
				}
			}
		}
	}
}